﻿/*******************************************************
Copyright © 2008-2009 Active Technologies Group, Inc. (ATGi)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/
using System;
using System.Text.RegularExpressions;
using System.Web.UI;
using ATGi.CS.Components;
using CommunityServer.Components;
using CommunityServer.Controls;

namespace ATGi.CS.Controls
{
    /// <summary>
    /// Viewer for video preview images attached to any post.
    /// </summary>
    public class PostVideoPreviewImageViewer : WrappedContentBase
    {
        #region Properties

        private Post _post = null;
        public override object DataSource
        {
            get
            {
                if (_post == null)
                    _post = CSControlUtility.Instance().GetCurrent<Post>(this);

                return _post;
            }
            set
            {
                if (value is Post)
                    _post = value as Post;
                else
                    throw new InvalidCastException("DataSource must be a valid Post object");
            }
        }

        /// <summary>
        /// Gets or sets the width of the view.
        /// </summary>
        /// <value>The width.</value>
        public int Width
        {
            get { return (int)(ViewState["Width"] ?? 0); }
            set { ViewState["Width"] = value; }
        }

        /// <summary>
        /// Gets or sets the height of the view.
        /// </summary>
        /// <value>The height.</value>
        public int Height
        {
            get { return (int)(ViewState["Height"] ?? 0); }
            set { ViewState["Height"] = value; }
        }

        /// <summary>
        /// Gets or sets the type of view.
        /// </summary>
        /// <value>The type of the view.</value>
        public FileViewType ViewType
        {
            get { return (FileViewType)(ViewState["ViewType"] ?? FileViewType.View); }
            set { ViewState["ViewType"] = value; }
        }

        #endregion

        protected override void BindDefaultContent(Control control, System.Web.UI.IDataItemContainer dataItemContainer)
        {
            // Don't display anything if the post is null or has no attachment.
            Post post = this.DataSource as Post;
            if (post == null || post.Attachment == null)
            {
                this.AutomatedVisible = false;
                return;
            }

            string renderedViewer = null;

            // Perform custom logic to display previews.
            if (this.ViewType == FileViewType.Preview)
            {
                const string YOUTUBE_PREVIEW_URL_FORMAT = @"http://i.ytimg.com/vi/{0}/default.jpg";
                
                if (renderedViewer == null)
                    renderedViewer = RenderWebVideoPreviewViewer(post.AttachmentFilename, CSRegex.YouTubeFileViewerRegex(), YOUTUBE_PREVIEW_URL_FORMAT);

                if (renderedViewer == null)
                {
                    // Attempt to retrieve the CFS file for the post preview.
                    ICentralizedFile previewFile = VideoPreviewImageModule.GetPreviewFile(post.Attachment);

                    if (previewFile != null)
                    {
                        // Retrieve the preview file viewer.
                        renderedViewer = FileViewers.Render(previewFile, this.ViewType, this.Width, this.Height);
                    }
                    else
                    {
                        // If no preview file exists, then attempt to retrieve the normal file viewer.
                        renderedViewer = FileViewers.Render(post.Attachment, this.ViewType, this.Width, this.Height);
                    }
                }
            }
            else
            {
                // Display a standard file viewer when not viewing a preview.
                renderedViewer = FileViewers.Render(post.Attachment, this.ViewType, this.Width, this.Height);
            }

            if (string.IsNullOrEmpty(renderedViewer))
                this.AutomatedVisible = false;
            else
                control.Controls.Add(new LiteralControl(renderedViewer));
        }

        private string RenderWebVideoPreviewViewer(string attachmentFilename, Regex fileViewerRegex, string previewUrlFormat)
        {
            Match match = fileViewerRegex.Match(attachmentFilename);
            if (match.Success)
            {
                string previewImageUrl = string.Format(previewUrlFormat, match.Groups[1].Value, this.Width, this.Height);

                return FileViewers.Render(new Uri(previewImageUrl), this.ViewType, this.Width, this.Height);
            }
            else
                return null;
        }
    }
}
